<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Models\Admins;
use App\Models\Order;
use App\Models\Role;
use App\Models\Rule;
use Carbon\Carbon;
use Illuminate\Http\Client\HttpClientException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

use Illuminate\Http\Exceptions\HttpResponseException;
use MongoDB\Driver\BulkWrite;

class AdminController extends BaseController
{

    /**
     * 登錄
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(LoginRequest $request)
    {

        $username = $request->input('username');
        $password = $request->input('password');

        $user = Admins::where('username', $username)->first();
        if (!$user) return $this->apiError('賬號密碼錯誤');
        if (!password_verify($password, $user->password)) return $this->apiError('賬號密碼錯誤!');


        $token=$this->CreateSaveToken($user->id);
        return $this->success(['token'=>$token]);

    }


    private function CreateSaveToken($arr =null)
    {
        // 生成token
        $token = sha1(md5(uniqid(md5(microtime(true)), true)));
//        $arr['token'] = $token;
        // 登录过期时间 604800 一周
        Redis::setex($token,604800,$arr);
        // 保存到缓存中

        // 返回token
        return $token;
    }


    public function register(Request $request)
    {
       $username=$request->input('username');
       $password=bcrypt($request->input('password'));

        Admins::create(['username'=>$username,'password'=>$password,'role_id'=>$request->input('role_id')]);
        return  $this->success();

    }

    public function get(Request $request)
    {
        return auth()->id();

    }

    /**
     * 退出登錄
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginOut(Request $request)
    {
        auth()->logout();
        return $this->success();
    }

    public function getinfo()
    {
        $role=Admins::find(request()->adminId);
//

        if($role->role_id==1){

            $menu=Rule::where('is_menu',1)->orderBy('sort','desc')->get();
        }else{
            $rule=Role::find($role->role_id);

            $menu=Rule::where('is_menu',1)->orderBy('sort','desc')->whereIn('id',explode(',',$rule->rule_id))->get();

        }

        $menu=$this->tree($menu);


//        return $this->success(compact('role','menu'));
        return $this->success($menu);
    }


    public function menus()
    {

            $menu=Rule::orderBy('sort','desc')->get()->toArray();

        $menu=$this->getTree($menu);


//        return $this->success(compact('role','menu'));
        return $this->success($menu);
    }

    protected function tree($arr,$pid=0)
    {
        $data=[];
        foreach ($arr as $key=>$item){
            if($item['pid']==$pid){
                $data[$key]=$item;
                $data[$key]['child']=$this->tree($arr,$item['id']);
            }
        }
        return array_values($data);
    }

    protected function getTree(array $data)
    {
        $items = [];
        foreach ($data as $v){
            $items[$v['id']] = $v; // $items[1] =
        }
        $tree = array(); //格式化好的树
        foreach ($items as $item)
            if (isset($items[$item['pid']]))
                $items[$item['pid']]['chlid'][] = &$items[$item['id']];
            else
                $tree[] = &$items[$item['id']];
        return $tree;
    }

    /**
     * 修改密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updatePassword(Request $request)
    {
        $id=$request->input('id');
        if(!$id){
            $this->error('id不能为空');
        }


        if(Admins::where('id',$id)->update($request->all())) return $this->success();
        $this->error();
    }

    //获取管理列表
    public function getAdmin(Request $request)
    {
        $keyword=$request->input('keyword');
//        $where=[];
//        if(!empty($keyword)){
//            $where[]=['username'=>'like',"%$keyword%"];
//        }
       $data= Admins::when($keyword,function($query) use($keyword){
           $query->where('username','like',"%$keyword%")->get();
       })->with(['role'])->paginate($request->input('limit',10));
       $role=Role::get();

       return $this->success(compact('data','role'));
    }

    public function destroy($id)
    {

        if( Admins::destroy($id)) return $this->success();
        $this->error('刪除失敗');
    }

//    public function getTree($menu,$pid=0){
//        $res = [];
//        if(empty($menu)){
//            return $res;
//        }else{
//            foreach ($menu as $key => $value) {
//                if ($value['pid'] == $pid) {
//                    $res[$key] = $value;
//                    $res[$key]['children'] = $this->getTree($menu, $value['id']);
//                }
//            }
//            return $res;
//        }
//    }

//    public function dynamic()
//    {
//
//        $user=DB::table('users')->count();
//        $order=DB::table('order')->where('status',50)->count();
//        $totalOrder=DB::table('order')->where('status','>',10)->count();
//        $totalSale=DB::table('coupon')->count();
//       $data=[   "panels"=>[
//           [
//               "title"=>"支付訂單",
//               "value"=>$order,
//               "unit"=>"年",
//               "unitColor"=>"success",
//               "subTitle"=>"總支付訂單",
//               "subValue"=>$order,
//               "subUnit"=>""
//           ],
//           [
//               "title"=>"訂單",
//               "value"=>$totalOrder,
//               "unit"=>"周",
//               "unitColor"=>"danger",
//               "subTitle"=>"轉化率",
//               "subValue"=>"60%",
//               "subUnit"=>""
//           ],
//           [
//               "title"=>"優惠券",
//               "value"=>$totalSale,
//               "unit"=>"",
//               "unitColor"=>"",
//               "subTitle"=>"優惠券數量",
//               "subValue"=>$totalSale,
//               "subUnit"=>""
//           ],
//           [
//               "title"=>"新增用戶",
//               "value"=>$user,
//               "unit"=>"年",
//               "unitColor"=>"warning",
//               "subTitle"=>"總用戶",
//               "subValue"=>$user,
//               "subUnit"=>"人"
//           ]
//       ]];
//        return $this->success($data);
//    }

    public function dynamic()
    {

        $data=Order::with('detail.products')->orderBy('id','desc')->paginate(6);

        return $this->success($data);
    }
}

